package com.example.word.ui.activity;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.example.dict.R;
import com.example.word.bean.Dict;
import com.example.word.bean.StudyPlan;
import com.example.word.bean.User;
import com.example.word.bean.Word;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.widget.ActionBar;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * 学习计划
 */
public class StudyPlanActivity extends AppCompatActivity {
    private Activity mActivity;
    private ActionBar mTitleBar;//标题栏
    private TextView tvAccount, tvDayTask;
    private Button btnSave;//保存
    private Spinner dictSelect;
    private String account;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_study_plan);
        mActivity = this;
        tvAccount = findViewById(R.id.tv_account);
        tvDayTask = findViewById(R.id.dayTask);
        btnSave = findViewById(R.id.btn_save);
        dictSelect = findViewById(R.id.dictSelect);
        mTitleBar = (ActionBar) findViewById(R.id.myActionBar);
        mTitleBar.setData(mActivity, "学习计划", R.drawable.ic_back, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        // 设置主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            btnSave.setBackground(getResources().getDrawable(R.drawable.btn_border_fill));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
            btnSave.setBackground(getResources().getDrawable(R.drawable.btn_border_fill_my_color));
        }
        initView();
    }

    private void initView() {
        account = (String) SPUtils.get(mActivity, "account", "");
        List<Dict> dictList = Dict.findAll(Dict.class);
        List<String> itemsArray = new ArrayList<>();
        for (Dict dict : dictList) {
            itemsArray.add(dict.getTitle());
        }
        // 创建 ArrayAdapter 并设置下拉选项的样式
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, itemsArray);
        // 设置下拉列表的样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // 将适配器设置到 Spinner
        dictSelect.setAdapter(adapter);

        // 获取当前用户信息
        User user = DataSupport.where("account = ?", account).findFirst(User.class);
        if (user != null) {
            tvAccount.setText(user.getAccount() + " (" + user.getNickName() + ")");
        }
        StudyPlan studyPlan = StudyPlan.where("account = ?", account).findFirst(StudyPlan.class);
        tvDayTask.setText(String.valueOf(studyPlan.getDayTask()));
        dictSelect.setSelection(itemsArray.indexOf(studyPlan.getDict()));
//        Map<String, String> requestParam = new HashMap<>();
//        requestParam.put("account", account);
//        HttpUtils.sendGetRequest("/getUserByAccount", requestParam, User.class, new HttpUtils.ApiCallback<User>() {
//            @Override
//            public void onSuccess(Response<User> response) {
//                // 处理请求成功的情况
//                User user = response.getData();
//                // 跳转页面
//                tvAccount.setText(user.getAccount());
//                etNickName.setText(user.getNickName());
//                etAge.setText(String.valueOf(user.getPhoneNumber()));
//            }
//
//            @Override
//            public void onFailure(Response response) {
//                // 处理请求失败的情况
//                MessageUtils.show(response.getMsg(), mActivity);
//            }
//        });
        //保存
        btnSave.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {
                int dayTask = 0;
                String dict = null;
                try {
                    dayTask = Integer.parseInt(tvDayTask.getText().toString());
                    dict = dictSelect.getSelectedItem().toString();
                } catch (Exception e) {
                    MessageUtils.show("请填写完整信息", mActivity);
                    return;
                }

                if ("".equals(dict)) {
                    MessageUtils.show("词汇不能为空", mActivity);
                    return;
                }
                if (dayTask <= 0) {
                    MessageUtils.show("任务数必须大于0", mActivity);
                    return;
                }

                StudyPlan studyPlan = DataSupport.where("account = ?", account).findFirst(StudyPlan.class);
                studyPlan.setDict(dict);
                studyPlan.setDayTask(dayTask);
                studyPlan.save();
                MessageUtils.show("保存成功！", mActivity);

                studyPlan = StudyPlan.queryCurrentUserPlan(account);
                String message = String.format("您正在学习【%s】每天目标为%s个单词！", studyPlan.getDict(), studyPlan.getDayTask());

                sendNotify(message, mActivity);

                finish();//关闭页面
            }
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void sendNotify(String message, Context context) {
        StudyPlan studyPlan;// 创建通知渠道（仅适用于 Android 8.0 及以上）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("channel_id", "Channel Name", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("Channel Description");
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

        // 创建通知
        Notification.Builder builder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            builder = new Notification.Builder(context, "channel_id")
                    .setSmallIcon(R.drawable.a1)
                    .setContentTitle("学习计划制定成功")
                    .setContentText(message)
                    .setPriority(Notification.PRIORITY_DEFAULT);
        }

        // 使用通知管理器显示通知
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.notify((int) Math.floor(Math.random() * 10), builder.build());
    }
}
